<template>
    <div>
        <el-row>
            <el-col :span="6">
                <el-card :body-style="{ margin: '10px',padding: '5px' }">
                    <el-form ref="patientform" :model="patientform" label-width="80px" label-position="left">
                        <el-form-item label="患者姓名">
                            <el-input v-model="patientform.patientName" readonly>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="身份证号">
                            <el-input v-model="patientform.idCard" readonly></el-input>
                        </el-form-item>
                        <el-form-item label="患者电话">
                            <el-input v-model="patientform.tel" readonly></el-input>
                        </el-form-item>
                        <el-form-item label="性别: " prop="gender">
                        <dict-tag :options="dict.type.his_doctor_sex" :value="patientform.gender"/>
                        </el-form-item>
                        <el-form-item label="出生日期" prop="patientDate">
                            <el-date-picker clearable v-model="patientform.patientDate" type="date"
                                value-format="yyyy-MM-dd" placeholder="" readonly>
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="患者年龄" prop="age">
                            <el-input v-model="patientform.age" placeholder="" readonly/>
                        </el-form-item>
                        <el-form-item label="地址信息" prop="address">
                            <el-input v-model="patientform.address" placeholder="" type="textarea" readonly/>
                        </el-form-item>
                        <el-form-item label="过敏史" prop="allergy">
                            <el-input v-model="patientform.allergy" placeholder="" type="textarea" readonly />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="newone">新开就诊</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
            <el-col :span="18">
                <el-card :body-style="{ margin: '5px',padding: '5px' }">
                    <el-tabs v-model="activeName2" type="border-card">
                        <el-tab-pane label="病例" name="first">
                            <el-form ref="treatform" :model="treatform" label-width="80px" size="mini"
                                label-position="left">
                                <el-form-item label="病例编号" prop="treatID" >
                                    <el-input v-model="treatID" placeholder="保存后获取病例编号" disabled style="width: 200px"/>
                                </el-form-item>
                                <el-form-item label="发病日期" prop="treatDate">
                                    <el-date-picker clearable v-model="treatform.treatDate" type="date"
                                        value-format="yyyy-MM-dd" placeholder="请选择就诊日期">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="是否传染" prop="treatContagion">
                                    <el-select v-model="treatform.treatContagion" placeholder="请选择是否传染" clearable>
                                        <el-option v-for="dict in dict.type.his_treat_contagion" :key="dict.value"
                                            :label="dict.label" :value="dict.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="主诉" prop="treatComplaint">
                                    <el-input v-model="treatform.treatComplaint" placeholder="请输入主诉" type="textarea"
                                        maxlength="100" show-word-limit />
                                </el-form-item>
                                <el-form-item label="诊断信息" prop="info">
                                    <el-input v-model="treatform.treatInfo" placeholder="请输入诊断信息" type="textarea"
                                        maxlength="100" show-word-limit />
                                </el-form-item>
                                <el-form-item label="医生建议" prop="treatAdvice">
                                    <el-input v-model="treatform.treatAdvice" placeholder="请输入医生建议" type="textarea"
                                        maxlength="100" show-word-limit />
                                </el-form-item>
                                <el-form-item label="备注" prop="remark">
                                    <el-input v-model="treatform.remark" placeholder="请输入备注" type="textarea"
                                        maxlength="250" show-word-limit />
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="success" @click="add">保存病例</el-button>
                                    <el-button type="success" @click="updateReg">就诊完成</el-button>
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane label="药品处方" name="second">
                            <el-button type="success" @click="openMedicineDialog">添加药品</el-button>
                            <el-table :data="prescriptionList" stripe border style="width: 100%">
                                <el-table-column label="名称" align="center" prop="prescriptionName" />
                                <el-table-column label="价格" align="center" prop="price" />
                                <el-table-column label="数量" align="center" prop="quantity" />
                                <el-table-column label="总价" align="center" prop="amount" />
                                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                <template slot-scope="scope">
                                <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-delete"
                                    @click="deletePrescription(scope.$index)"
                                >删除</el-button>
                                </template>
                            </el-table-column>
                            </el-table>
                        </el-tab-pane>

                    </el-tabs>
                </el-card>
            </el-col>
        </el-row>
        <!-- 选择挂号患者窗口-->
        <el-dialog title="选择挂号患者" :visible.sync="dialogTableVisible">
            <el-tabs v-model="activeName1" type="card" @tab-click="tabclick">
                <el-tab-pane label="待就诊列表" name="one">
                    <el-table :data="registrationList">
                        <el-table-column label="患者姓名" align="center" prop="patientName" />
                        <el-table-column label="流水编号" align="center" prop="registrationId" />
                        <el-table-column label="挂号类型" align="center" prop="scheduleType" />
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button size="mini" type="success" icon="el-icon-check"
                                    @click="handleUpdate(scope.row)">接诊
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList" />
                </el-tab-pane>
                <el-tab-pane label="就诊中列表" name="weo">
                    <el-table :data="registrationList">
                        <el-table-column label="患者姓名" align="center" prop="patientName" />
                        <el-table-column label="流水编号" align="center" prop="registrationId" />
                        <el-table-column label="挂号类型" align="center" prop="scheduleType" />
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button size="mini" type="success" icon="el-icon-check"
                                    @click="handleUpdate(scope.row)">接诊
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList" />
                </el-tab-pane>
                <el-tab-pane label="就诊完成列表" name="three">
                    <el-table :data="registrationList">
                        <el-table-column label="患者姓名" align="center" prop="patientName" />
                        <el-table-column label="流水编号" align="center" prop="registrationId" />
                        <el-table-column label="挂号类型" align="center" prop="scheduleType" />
                    </el-table>
                    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList" />
                </el-tab-pane>
            </el-tabs>
        </el-dialog>

        <!-- 选择药品窗口 -->
        <el-dialog title="选择药品" :visible.sync="medicineDialogVisible">
        <el-table :data="medicineList" stripe border style="width: 100%" @row-click="handleRowClick">
            <el-table-column width="55">
            <template slot-scope="scope">
                <el-radio v-model="selectedMedicine.medicineId" :label="scope.row.medicineId">&nbsp;</el-radio>
            </template>
            </el-table-column>
            <el-table-column label="名称" align="center" prop="medicineName" />
            <el-table-column label="价格" align="center" prop="price" />
            <el-table-column label="数量" align="center">
            <template slot-scope="scope">
                <el-input-number v-model="scope.row.quantity" :min="1" :max="100" size="small" :disabled="scope.row.medicineId !== selectedMedicine.medicineId"></el-input-number>
            </template>
            </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button @click="closeMedicineDialog">取 消</el-button>
            <el-button type="primary" @click="saveSelectedMedicine">确 定</el-button>
        </div>
        </el-dialog>
    </div>
</template>
  <script>
    import { getPatient, updatePatient } from "@/api/his/patient";
    import { getRegistration,getRegAndTreat,updateRegistration} from "@/api/his/registration";
    import { listTreat, addTreat, updateTreat ,getTreat} from "@/api/his/treat";
    import { listNewregistration, getNewregistration, delNewregistration, addNewregistration, updateNewregistration,getone } from "@/api/his/newregistration";
    import{ getUserProfile} from "@/api/system/user";
    import { listMedicine, addMedicine, updateMedicine, delMedicine, getMedicine } from "@/api/his/medicine";
    import { listInspect, addInspect, updateInspect, delInspect, getInspect } from "@/api/his/inspect";
    import { listNewprescription, getNewprescription, delNewprescription, addNewprescription, updateNewprescription,getNewone } from "@/api/his/newhisprescription";
  export default {
    dicts: ['his_treat_contagion','his_doctor_sex'],
    data() {

      return {
        //选择处方表
        prescriptionList:[],
        medicineList: [], // 药品列表
        selectedMedicine: { // 选中的药品及其数量
        medicineId: null,
        medicineName: null,
        price: null,
        num: null,
        },
         medicineDialogVisible: false,
        //检查列表
        inspectList:[],
        value:'',
        total: 0,
        dialogTableVisible:false,
        openM:false,
        openI:false,
        queryParams:{
          pageNum: 1,
          pageSize: 10,
          registrationStatus: 1,
        },
        // 挂号列表表格数据
        registrationList: [],
        //患者表单数据
        patientform: {
          patientName: '',
          idCard: '',
          tel: '',
          gender: '',
          patientDate: '',
          age:'',
          address: '',
          allergy: '',
          patientId:'',
        },
        registration:{
            registrationId:"",//挂号主键
            registrationStatus:"",//挂号状态

        },
        //就诊表单数据
        treatform:{
            treatRegistrationId:null,
            treatDate:null,
            treatContagion:null,
            treatComplaint:null,
            treatInfo:null,
            treatAdvice:null,
            patientId:null,
            patientName:null,
            doctId:null,
            doctName:null,
            remark:null,
            queueId:null,

        },
        newoneparam:{
            registrationDoctorName : null,
            registrationSchedule :null,
        },
        activeName1: 'one', //默认显示第一页
        activeName2: 'first', //默认显示第一页
        treatID : null,//就诊主键
        queueID : null,//挂号主键
        queryParam1:{
            pageNum: 1,
            pageSize: 10,
        }
      };
    },
    created() {
        this.getUserInfo();
      },
    methods: {

        addInspect(){
            //保存时遍历循环保存
            console.log(this.prescriptionList);
            for (let i = 0; i < this.prescriptionList.length; i++) {
                const element = this.prescriptionList[i];
                addNewprescription(element).then(response => {
                    if(response.code === 200){
                        this.$modal.msgSuccess("保存成功");
                    }
                });
            }

            // addInspect(prescriptionList).then(response => {
            //  if(response.code === 200){
            //     this.$modal.msgSuccess("保存成功");
            //  }
            // });
        },
        deletePrescription(index) {
    this.prescriptionList.splice(index, 1);
  },
        handleRowClick(row) {
        this.selectedMedicine = {
        medicineId: row.medicineId,
        medicineName: row.medicineName,
        price: row.price,
        num: row.quantity || 1,
        quantity: row.quantity || 1,
        };
     },
        closeMedicineDialog() {
            this.medicineDialogVisible = false;
        },
        // 获取当前日期
     getCurrentDate() {
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
     },
     // 根据登录ID获取登录用户详情信息
     getUserInfo() {
        getUserProfile().then(response => {
        this.newoneparam.registrationDoctorName = response.data.nickName;
        this.newoneparam.registrationSchedule = this.getCurrentDate();
      });
    },
        //新开就诊，直接获取挂号表单数据
        newone(){
            getone(this.newoneparam).then(response => {
                //如果没有数据提示当前无挂号信息
                if(response.data==null){
                    this.$modal.msgSuccess("当前无挂号信息");
                }
                this.patientform =response.data
                this.queueID = response.data.queueId
                if(response.data.treatId!=null){
                    getTreat(response.data.treatId).then(response => {
                        this.treatform = response.data
                        this.treatID = response.data.treatId
                    });
                }

            });
        },
        /**重置 */
        reset(){
        this.treatform={
            treatDate:null,
            treatContagion:null,
            treatComplaint:null,
            treatInfo:null,
            treatAdvice:null,
            remark:null,
            patientId:null,
            patientName:null,
            doctId:null,
            doctName:null,
        };
        this.patientform={
          patientName: '',
          idCard: '',
          tel: '',
          gender: '',
          patientDate: '',
          age:'',
          address: '',
          allergy: '',
          patientId:'',
        };
        this.registration={
            registrationId:"",//挂号主键
            registrationStatus:"",//挂号状态
            registrationNo:"",//挂号编号
        };
    },
    /**查询列表 */
      getList(){
        listTreat(this.queryParams).then(r => {
            this.registrationList = r.rows;
        });
      },
    //选择患者按钮操作
      checkpatient(){
        this.dialogTableVisible=true;
        this.getList();
      },
    /** 接诊按钮操作 */
    handleUpdate(row) {
        this.reset();
        this.dialogTableVisible=false;
        this.registration.registrationId=row.registrationId;
        this.registration.registrationStatus=row.registrationStatus;
        getRegistration(this.registration.registrationId).then(r1=>{//加载挂号ID,判断挂号状态加载不同的信息
            this.registration.registrationNo=r1.data.registrationNo;
            if(r1.code==200&&this.registration.registrationStatus==1){//加载待就诊患者信息
                this.patientform.patientId=r1.data.registrationPatientId;
                getPatient(r1.data.registrationPatientId).then(r2=>{
                    if(r2.code==200){
                        this.patientform=r2.data;
                    }
                });
            }else if(r1.code==200&&this.registration.registrationStatus==4){//加载就诊中患者信息
                this.patientform.patientId=r1.data.registrationPatientId;
                getPatient(r1.data.registrationPatientId).then(r2=>{
                    if(r2.code==200){
                        this.patientform=r2.data;
                        getRegAndTreat(this.registration.registrationId).then(r=>{//加载病例信息
                             if(r.code=200){
                                this.treatform=r.data
                             }
                        })
                    }
                });

            };
        });
    },
    /**更新患者信息按钮 */
    update(){
        updatePatient(this.patientform).then(r=>{
           if(r.code=200){
            this.$modal.msgSuccess("更新成功");
           }
        })
    },
    /**保存病例按钮 */
    add(){
        console.log(this.patientform.patientId)
        if(this.patientform.patientId==''){//无患者信息
            this.$message.error("请选择待就诊患者")
        }else {
            this.treatform.patientId=this.patientform.patientId;
            this.treatform.patientName=this.patientform.patientName;
            this.treatform.doctName=this.newoneparam.registrationDoctorName;
            this.treatform.queueId=this.queueID;
            addTreat(this.treatform).then(r=>{
                if(r.code=200){
                    this.$modal.msgSuccess("病历保存成功");
                    this.treatID=r.data;
                }
            });
        }
    },
    /**就诊完成按钮 */
    updateReg(){
        this.registration.registrationStatus=2;
        this.registration.registrationId=this.queueID;
        updateNewregistration(this.registration).then(r=>{
            if(r.code==200){
                this.addInspect();
                this.$modal.msgSuccess("就诊完成");
                this.reset();//清空
                this.treatID=null;
            }
        })

    },
    //选择挂号患者窗口的事件
    tabclick(tab, event) {
        if (tab.index == 0) {
        this.queryParams.registrationStatus=1;
      } else if (tab.index == 1) {
        this.queryParams.registrationStatus=4;
      } else {
        this.queryParams.registrationStatus=2;
      };
      this.getList();
    },

   addmedicine(){
    listMedicine(this.queryParam1).then(response => {
        this.medicineList = response.rows;
    })
   },
   selectMedicine(medicine) {
    this.selectedMedicine = {
      medicineId: medicine.medicineId,
      medicineName: medicine.medicineName,
      price: medicine.price,
      num: medicine.quantity, // 使用用户选择的数量
    };
   },
   saveSelectedMedicine() {
    if (this.selectedMedicine.medicineId) {
      this.prescriptionList.push({
        prescriptionId: this.selectedMedicine.medicineId,
        prescriptionName: this.selectedMedicine.medicineName,
        price: this.selectedMedicine.price,
        quantity: this.selectedMedicine.quantity,
        amount: this.selectedMedicine.price * this.selectedMedicine.quantity,
        treatId: this.treatID,
        state: "1"
      });
      this.medicineDialogVisible = false;
      this.resetSelectedMedicine();
    } else {
      this.$message.error("请选择药品");
    }
  },
  resetSelectedMedicine() {
    this.selectedMedicine = {
      medicineId: null,
      medicineName: '',
      price: 0,
      num: 1,
    };
  },

 openMedicineDialog() {
    if (this.treatID === null) {
      this.$message.error("请先保存病历");
      return;
    }
    this.addmedicine();
    this.medicineDialogVisible = true;
  },
},
  }
  </script>
